package com.tg.appcommon.android;

import com.tange.base.toolkit.DateUtil;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EcKey {
    private static final  String TAG ="EcKey";
    /* desKey = uuid */
    static private final byte[]iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
    static public String encKey(String desKey, String plain) {
        desKey = desKey.substring(desKey.length()-8);
        //byte []iv = uuid.substring(uuid.length()-8).getBytes(StandardCharsets.UTF_8);
        byte []bp = plain.getBytes(StandardCharsets.UTF_8);
        byte []bo = new byte[(bp.length + 7)/8*8];

        int i;
        for(i=0; i<bp.length; i++)
            bo[i] = bp[i];

        long utcTime = new Date().getTime() / 1000;
        String strTime = String.valueOf(utcTime);

        System.out.println("utc time: " + strTime);


        for(i=bp.length; i < bo.length; i++)
            bo[i] = (byte) (bo.length - bp.length + 0x30);
        for(i=0; i<bo.length; i++)
            bo[i] = (byte) (bo[i] ^ strTime.charAt(i % strTime.length()));

        System.out.println(bo);

        try {
            Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");
            SecretKeySpec key = new SecretKeySpec(desKey.getBytes(), "DES");
            IvParameterSpec Iv = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, key, Iv);
            byte[] encrypted = cipher.doFinal(bo);

            return strTime + " " + new String(Base64.getEncoder().encode(encrypted));
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    private static final String MAC_NAME = "HmacSHA1";
    static public String calcH1(String password, String userid, String uuid) throws NoSuchAlgorithmException, InvalidKeyException {
        SecretKeySpec keySpec = new SecretKeySpec((userid+uuid).getBytes(StandardCharsets.UTF_8), MAC_NAME);
        Mac mac = Mac.getInstance(MAC_NAME);
        mac.init(keySpec);

        return new String(Base64.getEncoder().encode(mac.doFinal(password.getBytes())));
    }

    static public String calcH2(String h1, String uuid) throws NoSuchAlgorithmException, InvalidKeyException {
        SecretKeySpec keySpec = new SecretKeySpec(uuid.getBytes(StandardCharsets.UTF_8), MAC_NAME);
        Mac mac = Mac.getInstance(MAC_NAME);
        mac.init(keySpec);

        return new String(Base64.getEncoder().encode(mac.doFinal(h1.getBytes())));
    }

    static public String calcUnlockReq(String password, String userid, String uuid, String token) throws NoSuchAlgorithmException, InvalidKeyException {
        String h1 = calcH1(password, userid, uuid);
        String h2 = calcH2(h1, uuid);
        long utcTime = new Date().getTime() / 1000;
        String strTime = String.valueOf(utcTime);

        long time = System.currentTimeMillis();
        TGLog.d(String.valueOf(time / 1000));

        TGLog.d(TAG,"time = " + time + ", utcTime = " + utcTime + DateUtil.getStrToTime(time));

        SecretKeySpec ks = new SecretKeySpec(strTime.getBytes(), MAC_NAME);
        Mac mac = Mac.getInstance(MAC_NAME);
        mac.init(ks);

        mac.update(strTime.getBytes());
        mac.update(h2.getBytes());
        mac.update(token.getBytes());

        String sig = new String(Base64.getEncoder().encode(mac.doFinal()));

        return strTime + "," + token + "," + sig;
    }
    static public void main(String []args) {
        String out = encKey("1801057CIF4I", "123456");
        System.out.println(out);

        final String password = "12345678";
        final String userId = "123";
        final String uuid = "1801057CIF4I";
        final String token = "sgverBrSDVfweTVsdvSTvTVsdrVd24";

        System.out.println("==========================");
        System.out.println("password: " + password);
        System.out.println("userid: " + userId);
        System.out.println("uuid: " + uuid);
        System.out.println("token: " + token);
        System.out.println("==========================");

        String h1, h2, sig;
        try {
            h1 = calcH1(password, userId, uuid);
            h2 = calcH2(h1, uuid);
            sig = calcUnlockReq(password, userId, uuid, token);

            System.out.println("h1: " + h1);
            System.out.println("h2: " + h2);
            System.out.println("signature: " + sig);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
